<template>
    <view class="app-content">
        <view class="beforeAuth App_col" v-if="$util.isEmpty(wxUserInfo) && !loading">
            <view class="title">中装速配·获客大师</view>
            <view class="tip">成单率提高<text>5倍</text> 效率提高<text>10倍</text></view>
            <image :src="imgUrl+'login/efficiency.png'"></image>
            <button class="btn buttonPlain" open-type="getUserInfo" @getuserinfo="getUserInfo" :plain="true" hover-class="none">微信授权登录</button>
        </view>
        <view class="authed App_col" v-if="!$util.isEmpty(wxUserInfo) && !mobile && !loading">
            <view class="avatar">
                <image :src="wxUserInfo.avatarUrl"></image>
            </view>
            <view class="title">{{wxUserInfo.nickName}}</view>
            <view class="tip">亲，您已授权，快去获客吧!</view>
            <get-phone-number dataSource="wxAuth" @cbFn="getPhoneNum">
                <view class="btn">开启一键获客</view>
            </get-phone-number>
        </view>
		<view class="empty" v-show="loading"></view>

    </view>
</template>

<script>

import getPhoneNumber from '@/pages/components/getPhoneNumber'
import { wxLogin, postWxCode, getWxUserInfo } from '@/api/login'
import { checkLogin } from '@/api/common'
import { loginParmas } from '@/utils/common'
import { mapState, mapMutations } from 'vuex'

export default {
	components: {
		getPhoneNumber
	},
	data() {
		return {
			imgUrl: this.$constant.imgUrl,
			wxUserInfo: {},
			loading: true,
			mobile: ''
		}
	},
	onLoad(option) {
		this.option = option
		this.init()
	},
	created() {
		uni.showLoading({
			title: '加载中...'
		})
		this.mobile = uni.getStorageSync('wxMobile')
	},
	watch: {
		loading(val) {
			if (val) {
				uni.showLoading({
					title: '加载中...'
				})
			} else {
				uni.hideLoading()
			}
		}
	},
	computed: {
		...mapState({
			loginInfo: state => state.login.loginInfo
		})

	},
	methods: {
		...mapMutations(['setLoginInfo']),
		init() {
			uni.login({
				provider: 'weixin',
				success: res => {
					uni.setStorageSync('code', res.code)
					console.log(res.code, 'res.code')
					postWxCode({ code: res.code }).then(subRes => {
						const { openid, session_key, unionid } = subRes.data
						this.setLoginInfo({
							openid,
							session_key,
							unionid
						})
						uni.getUserInfo({
							provider: 'weixin',
							success: sSubRes => {
								this.getWxUserInfo(sSubRes.iv, sSubRes.encryptedData).then(() => {
									uni.getStorage({
										key: 'wxMobile',
										success: () => {
											this.wxLogin()
										},
										complete: () => {
											this.loading = false
										}
									})
								})
							},
							fail: () => {
								this.loading = false
							}
						})
					})
				}
			})
		},
		getPhoneNum() {
			uni.getStorage({
				key: 'wxMobile',
				success: res => {
					this.mobile = res.data
					this.wxLogin()
				}
			})
		},
		getUserInfo(e) {
			if (e.mp.detail.errMsg === 'getUserInfo:fail auth deny' || !e.mp.detail.iv) {
				return
			}
			this.getWxUserInfo(e.detail.iv, e.detail.encryptedData).then(() => {
				uni.getStorage({
					key: 'wxMobile',
					success: () => {
						this.wxLogin()
					},
					complete: () => {
						this.loading = false
					}
				})
			})
		},
		getWxUserInfo(iv, encryptedData) {
			this.loading = true
			const params = {
				sessionKey: this.loginInfo.session_key,
				iv,
				encryptData: encryptedData
			}
			return getWxUserInfo(params).then(res => {
				const { avatarUrl, city, country, gender, language, nickName, province } = res.data
				this.wxUserInfo = { avatarUrl, city, country, gender, language, nickName, province }
			})
		},
		wxLogin(isType = false) {
			this.loading = true
			const params = {
				parent_id: '',
				phoneNumber: uni.getStorageSync('wxMobile'),
				userInfo: this.wxUserInfo,
				scopeSessions: this.loginInfo
			}
			const { share_user_id } = this.option
			if (share_user_id) {
				params.parent_id = share_user_id
			}
			wxLogin(params).then(res => {
				uni.setStorage({
					key: 'token',
					data: res.data,
					success: () => {
						checkLogin().then(subRes => {
							this.loading = false
							const { user_id, token, type, role_id, subscribe } = subRes.data
							uni.setStorageSync('user_id', user_id)
							uni.setStorageSync('token', token)
							uni.setStorageSync('subscribe', subscribe)
							if (type === 'upgrade') {
								const query = loginParmas(this.option)
								uni.navigateTo({
									url: `/pages/login/loginIdentity/index${this.commonJS.queryData(query)}`
								})
								return
							}
							if (type === 'login' || isType) {
								const params = {
									owner_user_id: user_id,
									share_user_id: user_id
								}
								uni.navigateTo({
									url: `/pages/getGuest/shareIndex${this.$util.parse(params)}`
								})
								// uni.navigateTo({
								// 	url: `/pages/design/designCompany/indexNew${this.$util.parse(params)}`
								// })
								// uni.navigateTo({
								// 	url: `/pages/page/webview/index?user_id=${user_id}&role_id=${role_id}`
								// })
								// switch (role_id) {
								// 	case 1:
								// 		uni.redirectTo({
								// 			url: `/pages/design/designCompany/indexNew${this.commonJS.queryData(params)}`
								// 		})
								// 		break
								// 	case 3:
								// 		uni.redirectTo({
								// 			url: `/pages/design/designerIndex${this.commonJS.queryData(params)}`
								// 		})
								// 		break
								// 	default:
								// 		uni.redirectTo({
								// 			url: `/pages/page/webview/index`
								// 		})
								// 		break
								// }
							}
						}).catch(() => {
							uni.removeStorageSync('token')
						})
					}
				})
			})
		}

	}
}
</script>

<style scoped lang="scss">
.buttonPlain{
    border: none !important;
    padding: 0;
    margin: 0;
    width: auto;
    height: auto;
}
.app-content {
	box-sizing: border-box;
    padding-top: 220px;
	background-color: #fff;
	.empty {
		width: 100%;
		width: 100vw;
		height: 100%;
		height: 100vh;
		background-color: #fff;
		position: fixed;
		z-index: 1000;
	}
    .beforeAuth {
        .tip {
            margin-top: 29px;
            text {
                color: #FF6900
            }
        }
        image {
            width: 326px;
            height: 261px;
            margin: 70px auto 0;
        }
    }
    .authed {
        .avatar {
            width: 160px;
            height: 160px;
            border-radius: 50%;
            overflow: hidden;
            image {
                width: 100%;
                height: 100%;
            }
        }
        .title {
            margin-top: 31px;
        }
        .tip {
            margin-top: 108px;
        }
    }
    .title {
        text-align: center;
        font-size:48px;
        font-weight:600;
        color:rgba(57,27,6,1);
    }
    .tip {
        font-size:36px;
        color: #999;
    }
    .btn {
        position: fixed;
        left: 0;
        right: 0;
        bottom: 190px;
        margin: auto;
        width: calc(100vw - 100px);
        height:100px;
        line-height: 100px;
        text-align: center;
        background:rgba(255,209,26,1);
        border-radius:50px;
        font-size:36px;
        font-weight:600;
        color:rgba(58,27,4,1);
    }
}

</style>
